package cn.by.wms.service;

import cn.by.wms.dao.PoItemDao;
import cn.by.wms.dto.PoStatusDto;
import cn.by.wms.enums.PoStatus;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.smart.core.exception.BizException;
import cn.smart.core.util.UserSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.by.wms.entity.*;
import cn.by.wms.dao.PoMasterDao;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
/**
 * ;(206_po_master)表服务实现类
 * @author : heimi
 * @date : 2024-11-25
 */
@Service
@Slf4j
public class PoMasterService {
     
    @Autowired
    private PoMasterDao poMasterDao;
    @Autowired
    private PoItemDao poItemDao;
    
    public List<PoMaster> select(PoMasterQuery query) {

        return poMasterDao.select(query);
    }

    public Integer insert(PoMaster poMaster) {
        String nickName = UserSessionContext.get().getNickName();
        //生成当前的采购单单号
        String poId="PO"+ DateUtil.format(DateUtil.date(),"yyyyMMddHHmmssSSS");
        //给表头设置单号
        poMaster.setId(poId);
        //设置状态
        poMaster.setStatus(PoStatus.APPROVE.getCode());
        //取出具体的采购清单
        List<PoItem> poItems = poMaster.getPoItems();
        BigDecimal totalPrice=BigDecimal.ZERO;
        //给采购清单的每一列数据加上当前单号
        for (PoItem poItem : poItems) {
            poItem.setLastUpdateBy(nickName);
            poItem.setPoId(poId);
            //计算总价
            totalPrice =NumberUtil.add( totalPrice,NumberUtil.mul(poItem.getPrice(),poItem.getQty()));
        }
        //校验金额是否正确
        if (poMaster.getTotalPrice()!=totalPrice.doubleValue()){
            BizException.throwBizException(453, "金额异常");
        }
        if (totalPrice.doubleValue()>2000){
            //发送钉钉通知
            sendDingDing(poId,totalPrice);
        }else {
            poMaster.setStatus(PoStatus.TRANSFER.getCode());
        }
        PoMasterService proxyObject = (PoMasterService) AopContext.currentProxy();
        proxyObject.save(poMaster);
        return 0;
    }
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public void save(PoMaster poMaster){
        //插入具体采购清单
        poItemDao.insertBatch(poMaster.getPoItems());
        //插入具体采购单
       poMasterDao.insert(poMaster);

    }
    
    public Integer update(PoStatusDto poStatusDto) {
        return poMasterDao.update(poStatusDto);
    }
    
    public Integer delete(Integer id) {
        return poMasterDao.delete(id);
    }

    private static  final String dingdingUrl = "https://oapi.dingtalk.com/robot/send?access_token=a0324d6b8e9ce68c97725853cdd08c4b234e5ec394fc53de18ce6a3a41a9790b";
    private void  sendDingDing(String poId,BigDecimal totalPrice){
        JSONObject json1 = JSONUtil.createObj();
        json1.putOpt("msgtype","text");
        String msg = StrUtil.format("告警:{} 的采购单金额为：{}，需要您尽快审核", UserSessionContext.get().getNickName(),totalPrice);
        json1.putOpt("text",JSONUtil.createObj().putOpt("content",msg));
        JSONArray array = JSONUtil.createArray();
        array.add("15237666940");
        array.add("18537866710");
        json1.putOpt("at",JSONUtil.createObj().putOpt("isAtAll",false).putOpt("atMobiles",array));
        String json = JSONUtil.toJsonStr(json1);
        String result = HttpRequest.post(dingdingUrl)
                .body(json)
                .execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(result);
        Object errcode = jsonObject.get("errcode");
        if(errcode.equals(0)){
            log.debug("发送钉钉成功");
        }else{
            log.error("发送钉钉失败：{}",jsonObject.get("errmsg"));
        }

    }
 
}